package com.lemon.rule.express.instruction.detail;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lemon.rule.express.InstructionSet;
import com.lemon.rule.express.InstructionSetRunner;
import com.lemon.rule.express.OperateData;
import com.lemon.rule.express.RunEnvironment;
import com.lemon.rule.express.instruction.OperateDataCacheManager;

public class InstructionCallMacro extends Instruction {

    private static final Logger logger = LoggerFactory.getLogger(InstructionCallMacro.class);

    private String name;

    public InstructionCallMacro(String aName) {
        this.name = aName;
    }

    public void execute(RunEnvironment environment, List<String> errorList) throws Exception {
        if (environment.isTrace() && logger.isDebugEnabled()) {
            logger.debug(toString());
        }
        Object functionSet = environment.getContext().getSymbol(this.name);

        Object result = InstructionSetRunner.execute(environment.getContext().getExpressRunner(), new InstructionSet[] { (InstructionSet) functionSet }, environment.getContext().getExpressLoader(), environment.getContext(), errorList, environment.isTrace(), false, false, environment.getContext().isSupportDynamicFieldName());
        if (result instanceof OperateData) {
            environment.push((OperateData) result);
        } else {
            environment.push(OperateDataCacheManager.fetchOperateData(result, null));
        }

        environment.programPointAddOne();
    }

    public String toString() {
        return "call macro " + this.name;
    }
}